package com.xdqzy.baseline.common.aspect;

import com.xdqzy.baseline.common.annotation.LogTag;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author : winter
 * @version V1.0
 * @Title: 打印日志的切面
 * @ClassName : com.xdqzy.baseline.common.aspect.LogPrintAdvice.java
 * @Description :
 * @date :  2020-10-27 21:12
 */
@Component
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class LogPrintAdvice {
    private static final Logger LOGGER = LoggerFactory.getLogger("methodLogger");


    @Around(value = "@annotation(logTag)", argNames = "joinPoint,logTag")
    public Object handleLogAspect(ProceedingJoinPoint joinPoint, LogTag logTag) throws Throwable {
        long start = System.currentTimeMillis();
        Signature signature = joinPoint.getSignature();
        Object[] args = joinPoint.getArgs();
        LOGGER.info("开始执行方法:{} 操作类型:{} 参数:{}", signature, logTag.value(), logTag.showParam() ? args : "");
        boolean success = false;
        Object result = null;
        try {
            result = joinPoint.proceed();
            success = true;
            return result;
        } finally {
            long takeTime = System.currentTimeMillis() - start;
            if (takeTime > logTag.timeMillsThreshold()) {
                LOGGER.warn("执行方法:{} 完成 , 耗时: {}ms , 超过预设阈值 :{}ms ,返回结果: {} , 是否执行成功 :{}",
                        signature, takeTime, logTag.timeMillsThreshold(), logTag.showResult() ? result : "", success);
            } else {
                LOGGER.info("执行方法:{} 完成 , 耗时: {}ms  ,返回结果: {} , 是否执行成功 :{}",
                        signature, takeTime, logTag.showResult() ? result : "", success);
            }
        }
    }
}
